﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ReTool
{
    public static partial class ReHandler
    {

        /// <summary>
        /// 修改文件名 level 1
        /// </summary>
        /// <param name="filePath">原始文件绝对路径</param>
        /// <returns>新文件的绝对路径</returns>
        public static string ReFileName(string filePath)
        {
            FileInfo fi = new FileInfo(filePath);
            if (!fi.Exists)
            {
                Error($"文件 {filePath} 不存在", true);
                return string.Empty;
            }
            var destFileName = Path.Combine(fi.Directory.FullName, fi.Name.Replace(_option.Source, _option.Target));
            fi.MoveTo(destFileName);
            return destFileName;
        }

        /// <summary>
        /// 修改文件内容 level 2
        /// </summary>
        /// <param name="filePath">原始文件绝对路径</param>
        public static void ReFileContent(string filePath)
        {
            FileInfo fi = new FileInfo(filePath);
            if (!fi.Exists)
            {
                Error($"文件 {filePath} 不存在", true);
                return;
            }

            //剔除某些不支持直接修改内容的文件类型
            if (!string.IsNullOrEmpty(_option.Extensions))
            {
                var exs = _option.Extensions.Split(",");
                for (int i = 0, p = exs.Length; i < p; i++)
                {
                    if (!exs[i].StartsWith("."))
                    {
                        exs[i] = $".{exs[i]}";
                    }
                    exs[i] = exs[i].Trim().ToUpper();
                }
                if (exs.Contains(fi.Extension.ToUpper()))
                {
                    Warn($"文件 {fi.FullName} 类型被排除，内容未更改");
                    return;
                }
            }


            var bak = $"{filePath}.bak";
            using (var fs = fi.OpenText())
            {
                using (var bfs = new FileStream(bak, FileMode.OpenOrCreate))
                {
                    StreamWriter sw = new StreamWriter(bfs);
                    sw.AutoFlush = true;
                    string t = string.Empty;
                    while (!fs.EndOfStream)
                    {
                        t = fs.ReadLine();
                        sw.WriteLine(t.Replace(_option.Source, _option.Target));
                    }
                    bfs.Flush();
                    bfs.Close();
                }
                fs.Close();
            }
            FileInfo bakFi = new FileInfo(bak);
            bakFi.MoveTo(filePath, true);
        }
    }
}
